package net.ba.models
{
	import com.asual.swfaddress.SWFAddress;
	import com.asual.swfaddress.SWFAddressEvent;
	
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.states.State;
	
	import net.ba.utils.UtilFunctions;
	
	import org.gaeswf.ServiceRO;
	
	
	[Bindable]
	public class StatesModelLocator
	{
		public var topState:String;
		public var secondState:String;
		public var thirdState:String;
		
		//Singleton stuff--------------------
        private static var modelLocator:StatesModelLocator;
		public function StatesModelLocator()
		{   
			if ( net.ba.models.StatesModelLocator.modelLocator != null ) {
                throw new Error( "Only one ModelLocator instance should be instantiated" );        				
			}
            initialize();
		}

        public static function getInstance():StatesModelLocator
        {
            if ( modelLocator == null )
                modelLocator = new StatesModelLocator();
                
            return modelLocator;
       }       
	   // END of definition of Singleton      
	   
		private function initialize() : void {
		   	//Listen to SWFAddress events to change states
			SWFAddress.addEventListener(SWFAddressEvent.INIT, handleSWFAddressInit);
		}       
   
		private static function handleSWFAddressInit(event:SWFAddressEvent):void {
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE,handleSWFAddressChange);						
		}
		
		private static function handleSWFAddressChange(event:SWFAddressEvent):void {
			
			//get existing states in the app to check if the topLevel in the
			//url
			var _states:Array = new Array();
			for each (var s:State in Application.application.states) {
				_states.push(s.name);
			}
			
			//Check if the URL defines a state or is defined at all.
			if (event.pathNames[0] == undefined) {
				getInstance().topState = AppStates.TOP_START;
				SWFAddress.setValue(AppStates.TOP_START);
			} 
			else if (_states.indexOf(event.pathNames[0])<0 ) {
				getInstance().topState = AppStates.TOP_START;
				SWFAddress.setValue(AppStates.TOP_START);
				Alert.show('You have been redirected to the main page as your URL was wrong');				
			}
			else {
				getInstance().topState = event.pathNames[0];
			}
			
			//Direct link to a TaxonName
			if (event.pathNames[0] ==AppStates.TOP_BROWSE && event.pathNames[1] != null && event.pathNames[1].length>0 &&  isNaN(Model.activeTaxon.id)) {
				Application.application.taxBrowser.setActiveTaxonFromUrl(event.pathNames[1]);
				
				
			}
						
			(event.pathNames[1])? getInstance().secondState = event.pathNames[1]:getInstance().secondState='';
			(event.pathNames[2])? getInstance().thirdState = event.pathNames[2]: getInstance().thirdState = '';			
			
			
		}
		
		
		//Methods to get a TaxonName from the URL
		
		//find the guid for a taxonName
		private function getTaxonNameFromString(_name:String):void {
			
			//Call the service 
			execute("BaServices.getDistributionsByTaxonName", UtilFunctions.replaceAll(_name,'_',' '));	
			
		}		
		
		public function BaServices_getDistributionsByTaxonNameResponse(result:Object):void
		{			
			//id = (result.result as Array)[0].taxonId;			
			
		}
		
		public function BaServices_getDistributionsByTaxonNameFault(error:Object):void {
			Alert.show("Sorry, the URL is pointing to a non-existant TaxonName");
		}
		
		
		// Execute: Makes a service call
		protected function execute(serviceName:String, ...args):void
		{
			// Add the current 
			args.unshift(this);
			args.unshift(serviceName);
			ServiceRO.call.apply(ServiceRO.call, args);
		}		
	}
}